// const { fetchMedifoodDetails } = require("../../Service/CategoryService");

Page({
  data: {
    searchBoxes: [
      { id: 0, selectedOption: 'name', value: '' }
    ],
  },
  
  onInputConfirm(e) {
    //从子组件传过来的id,value,selectedOption
    const id = Number(e.detail.id);
    const value = e.detail.value;
    const selectedOption = e.detail.selectedOption;
    console.log(id,value,selectedOption);

    // 判断传入的 id 是否在 searchBoxes 中已经存在的索引
    const index = this.data.searchBoxes.findIndex(box => box.id === id);

    if (index !== -1) {
        // 如果存在，则更新对应的 selectedOption 和 value
        const updatedSearchBoxes = [...this.data.searchBoxes];
        updatedSearchBoxes[index] = { ...updatedSearchBoxes[index], selectedOption, value };

        this.setData({
            searchBoxes: updatedSearchBoxes
        });
    } else {
        // 如果不存在，则新增数组项
        const newSearchBox = { id, selectedOption, value };
        this.setData({
            searchBoxes: [...this.data.searchBoxes, newSearchBox]
        });
    }

      console.log("更新后的 searchBoxes:", this.data.searchBoxes); // 输出更新后的 searchBoxes
    
  },
  
  addSearchBox() {
    let newId = this.data.searchBoxes.length > 0 ? this.data.searchBoxes[this.data.searchBoxes.length - 1].id + 1 : 1;

    this.setData({
      searchBoxes: [...this.data.searchBoxes, { id: newId, selectedOption: 'name', value: '' }],
    });

  },
  
  onRemoveSearchBox(e) {
    const id = e.currentTarget.id;
    this.setData({
      searchBoxes: this.data.searchBoxes.filter(box => box.id != id),
    });
    console.log('删除后：',this.data.searchBoxes);
  },

  handleSearch() {
    const searchConditions = this.data.searchBoxes;
    //构造一个查询字符串，将多个搜索条件以URL参数的形式编码，方便在页面间传递或提交给服务器执行搜索
    const queryParams = searchConditions.map((condition, index) =>
    `id${index}=${condition.id}&selectedOption${index}=${condition.selectedOption}&value${index}=${encodeURIComponent(condition.value)}`
    ).join('&');

    try {
      wx.navigateTo({
        url: `/Not-tabbar/Search-List/Search-List?${queryParams}`
      }).catch(error => {
        console.error('导航失败:', error);
      });
    } catch (error) {
      console.error('导航到搜索列表失败:', error);
    }
  },
  handleReset() {
    console.log('点击了重置');
    this.setData({
      searchBoxes: [],
    });
    this.setData({
      searchBoxes: [
        { id: 0, selectedOption: 'name', value: '' }
      ],
    })
    console.log('重置之后的：',this.data.searchBoxes);
  }

  
});
